﻿using System.Linq;
using System.Xml.Linq;

namespace Comdiv.QWeb.Serialization.BxlParser {
	public class BxlXmlParser {
		private bool extractsingle;
		private bool lexdata;
		private bool safeanonymnames;

		public BxlXmlParser(bool nolexdata = false, bool safeanonym = false) {
			lexdata = true;
			Tokenizer = new BxlTokenizer();
			Generator = new BxlXmlGenerator();
			if (nolexdata) lexdata = false;
			if (safeanonym) safeanonymnames = true;
		}


		protected BxlXmlGenerator Generator { get; set; }

		protected BxlTokenizer Tokenizer { get; set; }

		public BxlXmlParser NoLexData {
			get {
				lexdata = false;
				return this;
			}
		}

		public BxlXmlParser SafeAnonymNames {
			get {
				safeanonymnames = true;
				return this;
			}
		}

		public BxlXmlParser ExtractSingle {
			get {
				extractsingle = true;
				return this;
			}
		}

		public XElement Parse(string input, string filename = "") {
			var result = Generator.Generate(Tokenizer.Tokenize(input, filename), filename, lexdata, safeanonymnames);
			if (extractsingle) {
				if (result.Elements().Count() == 1) {
					result = result.Elements().First();
				}
			}
			return result;
		}
	}
}